package com.tepth.maintenancesystem.view;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tepth.maintenancesystem.R;
import com.tepth.maintenancesystem.api.MaintainHttp;
import com.tepth.maintenancesystem.presenter.NFCMACAdapter;
import com.tepth.maintenancesystem.untils.FileUtils;
import com.tepth.maintenancesystem.untils.NFCInterface;
import com.tepth.maintenancesystem.untils.NFCManger;
import com.tepth.maintenancesystem.untils.Untils;

import java.util.ArrayList;
import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NFCDialogActivity extends AppCompatActivity implements NFCInterface {

    @BindView(R.id.tv_message)
    TextView tv_message;

    @BindView(R.id.nfc_loading)
    RelativeLayout nfc_loading;

    @BindView(R.id.nfc_message)
    RelativeLayout nfc_message;

    @BindView(R.id.nfcdialog_title)
    TextView nfcdialog_title;

    @BindView(R.id.rl_nfc_listview)
    RelativeLayout rl_nfc_listview;

    @BindView(R.id.lv_nfc)
    ListView list_nfc;

    private Context context;
    private byte[] msgBuffer;
    private String address;
    private NFCMACAdapter mac_adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfcdialog);
        context = this;
        ButterKnife.bind(this);
//        nfc_loading.setVisibility(View.VISIBLE);
//        address = FileUtils.getNFC_MAC_File(FileUtils.getInnerSDCardPath() + "/tepth/NFCMAC.txt").trim();
//        if(address.equals("")){
            address= Untils.getNFCMAC(context);
            if(address.equals("")){
                NFCManger.startScanAndGetDevicedList(this,context);
            }else{
                startNFCManger();
            }
//        }else{
//            startNFCManger();
//        }
        handler.sendEmptyMessage(8);
        list_nfc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                address= (String) mac_adapter.getItem(position);
                Untils.setNFCMAC(context,address);
                NFCManger.setStopGetDevicedList(true);
                startNFCManger();
                handler.sendEmptyMessage(8);
                handler.sendEmptyMessage(10);
            }
        });
    }

    private void startNFCManger(){
        switch (NFCManger.isConnection()) {
            case 0:
                NFCManger.createDeviceManager(context, this);
                break;
            case 1:
                NFCManger.startGetDevice(this,context);
                break;
            case 2:
                NFCManger.startGetCard(this);
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://正在搜索设备
                    tv_message.setText("正在搜索设备...");
                    break;
                case 1://正在连接设备
                    tv_message.setText("正在连接设备...");
                    break;
                case 2://设备连接成功，准备打卡
                    tv_message.setText("设备连接成功");
                    break;
                case 7:
                    nfc_loading.setVisibility(View.VISIBLE);
                    nfc_message.setVisibility(View.GONE);
                    tv_message.setText("正在搜索卡片...");
                    break;
                case 3://打卡成功
                    Intent result = new Intent();
                    result.putExtra("BarCodeContents", msgBuffer);
                    setResult(MaintainHttp.NFC_RESULTCODE, result);
                    finish();
                    break;
                case 4://设备连接中断，重新搜索设备
                    tv_message.setText("设备连接中断,重新搜索设备");
                    break;
                case 5://打开失败,请重新打卡
                    tv_message.setText("打卡失败,请重新打卡");
                    break;
                case 6:
                    nfc_loading.setVisibility(View.GONE);
                    nfc_message.setVisibility(View.VISIBLE);
                    break;
                case 8://读取到存储的MAC地址，更改标题栏
                    if(!address.equals(""))
                        nfcdialog_title.setText("已绑定设备："+address);
                    else
                        nfcdialog_title.setText("未绑定设备，请选择一个NFC设备绑定");
                    break;
                case 9://显示NFC列表
                    Vector<String> nfcList= (Vector<String>) msg.getData().getSerializable("nfcList");
                    if(nfcList.size()>0){
                        nfc_loading.setVisibility(View.GONE);
                        nfc_message.setVisibility(View.GONE);
                        rl_nfc_listview.setVisibility(View.VISIBLE);
                        if(mac_adapter==null){
                            mac_adapter=new NFCMACAdapter(context,nfcList);
                            list_nfc.setAdapter(mac_adapter);
                        }else{
                            mac_adapter.setNfcList(nfcList);
                            mac_adapter.notifyDataSetChanged();
                        }
                    }else{
                        nfc_loading.setVisibility(View.VISIBLE);
                        nfc_message.setVisibility(View.GONE);
                        rl_nfc_listview.setVisibility(View.GONE);
                        tv_message.setText("正在搜索设备...");
                    }
                    break;
                case 10://隐藏NFC列表
                    nfc_loading.setVisibility(View.VISIBLE);
                    nfc_message.setVisibility(View.GONE);
                    rl_nfc_listview.setVisibility(View.GONE);
                    tv_message.setText("正在搜索设备...");
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void searchDevice() {
        handler.sendEmptyMessage(0);
    }

    @Override
    public void connectionDevice() {
        handler.sendEmptyMessage(1);
    }

    @Override
    public void successConnectionDevice() {
        handler.sendEmptyMessage(2);
    }

    @Override
    public void searchCard() {
        handler.sendEmptyMessage(7);
    }

    @Override
    public void successCard(byte[] msgBuffer) {
        this.msgBuffer = msgBuffer;
        handler.sendEmptyMessage(3);
    }

    @Override
    public void errorCard() {
        handler.sendEmptyMessage(5);
    }

    @Override
    public void stopSearchCard() {
        handler.sendEmptyMessage(6);
    }

    @Override
    public void updateDeviceList(Vector<String> nfcList) {
        Bundle bundle=new Bundle();
        bundle.putSerializable("nfcList",nfcList);
        Message msg=new Message();
        msg.what=9;
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    @OnClick({R.id.nfc_message, R.id.btn_barcode, R.id.btn_cancel})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.nfc_message:
                NFCManger.startGetCard(this);
                break;
            case R.id.btn_barcode:
                setResult(MaintainHttp.RETURN_BARCODE);
                NFCManger.setStopGetDevicedList(true);
                NFCManger.stopSearchCard();
                finish();
                break;
            case R.id.btn_cancel:
                NFCManger.setStopGetDevicedList(true);
                NFCManger.stopSearchCard();
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        NFCManger.setStopGetDevicedList(true);
        NFCManger.stopSearchCard();
        super.onDestroy();
    }
}
